$(function() {
	console.log("uid:{$uid}")
	//qd地图起点，
	var qd,zd,departure={},destination={},leftheight=window.innerHeight-250,destination_w,estimated_time_w,is_return_w,pre_meter_w,is_unit=false;
	destination_w=$('.destination_w').html()  
	estimated_time_w=$('.estimated_time_w').html();
	is_return_w=$('.is_return_w').html();
	pre_meter_w=$('.pre_meter_w').html();
	$('.orders_left').css('height',leftheight);
	laydate.render({
	  elem: '#test5'
	  ,type: 'datetime'
	});
	var map = new AMap.Map('map', {
		resizeEnable: true,
		zoom: 10,
		center: [118.57, 24.82]
	});
	 var driving = new AMap.Driving({
        map: map,
        panel: "panel",
        extensions:'all',
        hideMarkers:true
   }); 
   	$('.car_type').on('click', function() {
   		if($('select[name="booking_type"]').val()==2){
			choosecar("{:url('models/index',['op'=>'search'])}?type=3")
		}else{
			choosecar("{:url('models/index',['op'=>'search'])}?type=2")
		}
	});
	$('.autodispatch').on('click', function() {
		
	})
	$('select[name="use_type"]').on('change',function(){
		if($(this).val()==1){
			$('select[name="pay_type"]').find('option[value="1"]').attr('disabled','1')
			}else{
				$('select[name="pay_type"]').find('option[value="1"]').removeAttr('disabled')
			}
		
	})
	$('select[name="booking_type"]').on('change',function(){
		map.clearMap()
		qd="";
		zd="";
		$('.departure_w').find('input').each(function(){
			$(this).val('')
		})
		if($(this).val()==2){
			clearinput($('.destination_w'))
			clearinput($('.estimated_time_w'))
			clearinput($('.is_return_w'))
			clearinput($('.pre_meter_w'))
			
		}else{
			$('.destination_w').css('display','block');
			$('.estimated_time_w').css('display','block');
			$('.is_return_w').css('display','block');
			$('.pre_meter_w').css('display','block');
			$('.destination_w').html(destination_w);
			$('.estimated_time_w').html(estimated_time_w);
			$('.is_return_w').html(is_return_w);
			$('.pre_meter_w').html(pre_meter_w);
		}
	})
	$('select[name="order_type"]').on('change',function(){
		if($('select[name="order_type"]').val()){
			if($('.car_type_id').val()){
				if($('.distance').val()){
					cost({car_type_id:$('.car_type_id').val(),estimate_mileage:$('.distance').val(),order_type:$('select[name="order_type"]').val(),is_return: $('select[name="is_return"]').val()})
				}else{
					
				}
			}else{
				
			}
		}else{
			
		}
	})
    $('select[name="is_return"]').on('change',function(){
        if($('select[name="order_type"]').val()){
            if($('.car_type_id').val()){
                if($('.distance').val()){
                    cost({car_type_id:$('.car_type_id').val(),estimate_mileage:$('.distance').val(),order_type:$('select[name="order_type"]').val(),is_return: $('select[name="is_return"]').val()})
                }else{

                }
            }else{

            }
        }else{

        }
    })
	$('.dispatch').on('click', function() {
		var data={}
		var allow=true
		formId=$(this).closest('form')
		formId.find('input').each(function(){
			if($(this).attr('name')){
				if($(this).data('check')){
					console.log($(this).val())
					if($(this).val()==''){
						Err($(this).data('msg'))
						allow=false
						return false
					}else{
						data[$(this).attr('name')]=$(this).val()
					}
				}else{
					data[$(this).attr('name')]=$(this).val()
				}
			}
		})
		formId.find('select').each(function(){
			data[$(this).attr('name')]=$(this).val()
			
		})

		if(allow){
			Load()
			$.ajax({
				type:"post",
				url:"{:url('/adminapi/order/orderApply')}",
				data:data,
				success:function(res){
					Load(1)
					console.log(res)
					
					if(res.code==1){
						Msg('下单成功')
						window.location.href='{:url("index")}?order_state=1'
					}else{
						Err(res.msg)
					}
				},
				error:function(){
					Load(1)
					Err('请求失败')
				}
			});
		}
		
	})
	$('.passenger_name').on('click',function(){
		choosecar("{:url('/admin/passenger/index',['op'=>'search'])}")
	})
	$('.orderer_name').on('click',function(){
		choosecar("{:url('/admin/passenger/index',['op'=>'search'])}")
	})
	$('.approval_name').on('click',function(){
		choosecar("{:url('/admin/passenger/index',['op'=>'search'])}?is_check=1")
	})
	$('.appointment_date').on('change',function(){
		$('input[name="appointment_time"]').val(atime())
	})
	$('.appointment_time').on('change',function(){
		$('input[name="appointment_time"]').val(atime())
	})
	$('.pre_fee').on('change',function(){
		$('input[name="pre_fee"]').val($(this).val())
	})
	
	var contextMenu = new AMap.ContextMenu(); //创建右键菜单
	//右键放大
	contextMenu.addItem("设为起点", function() {
		setdeparture(contextMenuPositon)
	}, 0);
	//右键缩小
	contextMenu.addItem("设为终点", function(e) {
		setdestination(contextMenuPositon)
	}, 1);
	var contextMenu1 = new AMap.ContextMenu(); //创建右键菜单
	//右键放大
	contextMenu1.addItem("设为起点", function() {
		setdeparture(contextMenuPositon)
	}, 0);
	//右键缩小
	
	//绑定鼠标右击事件——弹出右键菜单
	map.on('rightclick', function(e) {
		if($('select[name="booking_type"]').val()==2){
			contextMenu1.open(map, e.lnglat);
			contextMenuPositon = e.lnglat;
		}else{
			contextMenu.open(map, e.lnglat);
			contextMenuPositon = e.lnglat;
		}
	});

	//关键字搜索

	AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {

		var poiPicker = new PoiPicker({
			//city:'北京',
			input: 'pickerInput'
		});

		//初始化poiPicker
		poiPickerReady(poiPicker);
	});

	function poiPickerReady(poiPicker) {

		window.poiPicker = poiPicker;

		var marker = new AMap.Marker();

		var infoWindow = new AMap.InfoWindow({
			offset: new AMap.Pixel(0, -20)
		});

		//选取了某个POI
		poiPicker.on('poiPicked', function(poiResult) {

			var source = poiResult.source,
				poi = poiResult.item,
				info = {
					source: source,
					id: poi.id,
					name: poi.name,
					location: poi.location.toString(),
					address: poi.address
				};

			marker.setMap(map);
			
			//	            infoWindow.setMap(map);

			marker.setPosition(poi.location);
			map.setZoomAndCenter(10, poi.location);
			//查询点右击
			var contextMenu1 = new AMap.ContextMenu(); //创建右键菜单
				
				contextMenu1.addItem("设为起点", function() {
					setdeparture(marker.getPosition( ))
				}, 0);
				//右键缩小
				contextMenu1.addItem("设为终点", function(e) {
					setdestination(marker.getPosition( ))
				}, 1);
			
				//绑定鼠标右击事件——弹出右键菜单
				marker.on('rightclick', function(e) {
					contextMenu1.open(map, e.lnglat);
					contextMenuPositon = marker.getPosition();
				});
			
		});

	}
	function setdeparture(contextMenuPositon){
		if(qd){
			map.remove(qd);
		}else{
			
		}
		AMapUI.loadUI(['overlay/SimpleMarker'], function(SimpleMarker) {
			var iconStyles = SimpleMarker.getBuiltInIconStyles('fresh');
			qd = new SimpleMarker({
				//普通文本
				iconStyle: iconStyles[2],
				//图标文字
				iconLabel: {
					//A,B,C.....
					innerHTML: '起',
					style: {
						color: '#fff'
					}
				},
				map: map,
				position: contextMenuPositon
			});
			departure=contextMenuPositon
			$('.from_lat').val(departure.N)
			$('.from_lon').val(departure.L)
			AMap.plugin('AMap.Geocoder', function() {
				geocoder = new AMap.Geocoder({
					city: "010" //城市，默认：“全国”
				});
				geocoder.getAddress(contextMenuPositon, function(status, result) {
					if(status === 'complete' && result.info === 'OK') {
						//获得了有效的地址信息:
						address= result.regeocode.formattedAddress;
						
					} else {
						address="获取地址失败";
	
					}
					$('.departure').val(address)
				});
				
			})
			if(qd){
				if(zd){
					driving.search(new AMap.LngLat(departure.L,departure.N), new AMap.LngLat(destination.L, destination.N),function(status, result){
					
						var usedtime;
						var distance;
						if(result.routes[0].distance){
							$('input[type="pre_meter"]').val(result.routes[0].distance)
							distance= (result.routes[0].distance/1000).toFixed(2)
						}
						$('input[name="pre_time"]').val(result.routes[0].time)
						$('input[name="pre_meter"]').val(result.routes[0].distance)
						if(result.routes[0].time>3600){
							usedtime= parseInt(result.routes[0].time/3600)+"小时"+Math.round((result.routes[0].time-parseInt(result.routes[0].time/3600)*3600)/60)+'分钟'
						}else{
							usedtime=Math.round(result.routes[0].time/60)+'分钟'
						}
						
						$('.estimated_time').val(usedtime)
						$('.distance').val(distance)
						console.log($('select[name="order_type"]').val())
						if($('select[name="order_type"]').val()){
							if($('.car_type_id').val()){
								if($('.distance').val()){
									cost({car_type_id:$('.car_type_id').val(),estimate_mileage:$('.distance').val(),order_type:$('select[name="order_type"]').val(),is_return: $('select[name="is_return"]').val()})
								}else{
									Err('请在地图上右击选择出发地，目的地')
								}
							}else{
								Err('请选择车型')
							}
						}else{
							Err('请选择订单类型')
						}
					});
					ajaxprefee()
				}else{}
			}else{}
			qd.setMap(map);
		})
	}
	function setdestination(contextMenuPositon){
		if(zd){
			map.remove(zd);
		}else{
			
		}
		
		AMapUI.loadUI(['overlay/SimpleMarker'], function(SimpleMarker) {
			var iconStyles = SimpleMarker.getBuiltInIconStyles('fresh');
			
			zd = new SimpleMarker({
				//普通文本
				iconStyle: iconStyles[2],
				//图标文字
				iconLabel: {
					//A,B,C.....
					innerHTML: '终',
					style: {
						color: '#fff'
					}
				},
				map: map,
				position: contextMenuPositon
			});
			destination=contextMenuPositon
			$('.to_lat').val(destination.N)
			$('.to_lon').val(destination.L)
			AMap.plugin('AMap.Geocoder', function() {
				geocoder = new AMap.Geocoder({
					city: "010" //城市，默认：“全国”
				});
				geocoder.getAddress(contextMenuPositon, function(status, result) {
					if(status === 'complete' && result.info === 'OK') {
						//获得了有效的地址信息:
						address= result.regeocode.formattedAddress;
						
					} else {
						address="获取地址失败";
	
					}
					$('.destination').val(address)
				});
				
			})
			qd.setMap(map);
			if(qd){
				if(zd){
					driving.search(new AMap.LngLat(departure.L,departure.N), new AMap.LngLat(destination.L, destination.N),function(status, result){
						
						var usedtime;
						var distance;
						if(result.routes[0].distance){
							distance= (result.routes[0].distance/1000).toFixed(2)
						}
						$('input[name="pre_time"]').val(result.routes[0].time)
						$('input[name="pre_meter"]').val(result.routes[0].distance)
						if(result.routes[0].time>3600){
							usedtime= parseInt(result.routes[0].time/3600)+"小时"+Math.round((result.routes[0].time-parseInt(result.routes[0].time/3600)*3600)/60)+'分钟'
						}else{
							usedtime=Math.round(result.routes[0].time/60)+'分钟'
						}
						
						$('.estimated_time').val(usedtime)
						
						$('.distance').val(distance)
						if($('select[name="order_type"]').val()){
							if($('.car_type_id').val()){
								if($('.distance').val()){
									cost({car_type_id:$('.car_type_id').val(),estimate_mileage:$('.distance').val(),order_type:$('select[name="order_type"]').val(),is_return: $('select[name="is_return"]').val()})
								}else{
									Err('请在地图上右击选择出发地，目的地')
								}
							}else{
								Err('请选择车型')
							}
						}else{
							Err('请选择订单类型')
						}
						
					});
					ajaxprefee()
				}else{}
			}else{}
		})
	}
	function atime(){
		var time=$('.appointment_date').val()+" "+$('.appointment_time').val()
		return time
	}
	//隐藏输入框且清空输入框中的内容
	function clearinput(obj){
		obj.css('display','none')
		obj.html('')
	}
	function ajaxprefee(){
		console.log(111)
		$.ajax({
			type:'post',
			url:'',
			data:{},
			success:function(res){
				
			}
		})
	}
	//计算预计费用
	function cost(data){
		Load()
		$.ajax({
			type:'post',
			url:'{:url("/adminapi/Order/getOrderPreFee")}',
			data:data,
			success:function(res){
				Load(1)
				if(res.code==1){
					console.log(res)
					$('input[name="pre_fee"]').val(res.data.estimate_cost.toFixed(2));
				}else{
					Err(res.msg);
				}
			},
			error:function(){
				Err('预算失败');
			}
		})
	}
})